package cn.edu.zafu.bigdata.x.zcy_0217;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        int port = 1234; // 服务端端口号
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is running and waiting for client connection...");

        try {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected.");

                new Thread(new ClientHandler(clientSocket)).start();
            }
        } finally {
            serverSocket.close();
        }
    }

    private static class ClientHandler implements Runnable {
        private Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        public void run() {
            try {
                InputStream input = clientSocket.getInputStream();
                OutputStream output = clientSocket.getOutputStream();

                byte[] buffer = new byte[1024];
                while (true) {
                    int bytesRead = input.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }

                    String clientMessage = new String(buffer, 0, bytesRead);
                    System.out.println("Client: " + clientMessage);

                    String serverResponse = "Echo: " + clientMessage;
                    output.write(serverResponse.getBytes());
                }
            } catch (IOException e) {
                System.out.println("Error in client handler: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
